package com.linmo.personalcenter;

import com.linmo.questionmatcher.QuestionMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class EditDialogueDialog extends JDialog {
    private static final DialogueDatabaseManage dialogueManage = new DialogueDatabaseManage();
    private static final Logger log = LoggerFactory.getLogger(EditDialogueDialog.class);
    private  QuestionMatcher questionMatcher ; // 接收 QuestionMatcher 实例

    private JTable dialogueTable;
    private DefaultTableModel tableModel;
    private JButton addButton;
    private JButton deleteButton;
    private JButton editButton;
    private JButton saveButton;
    private List<DialogueDTO> originalDialogues;
    private List<DialogueDTO> modifiedDialogues;

    public EditDialogueDialog(JFrame parent, QuestionMatcher questionMatcher) {
        super(parent, "编辑对话语库", true);
        this.questionMatcher = questionMatcher;
        setSize(800, 600);
        setLocationRelativeTo(parent);

        setLayout(new BorderLayout());

        // 初始化表格模型
        tableModel = new DefaultTableModel(new String[]{"ID", "问题", "答案"}, 0);
        dialogueTable = new JTable(tableModel);
        dialogueTable.setDefaultEditor(Object.class, null); // 禁用所有单元格的编辑

        // 添加滚动条
        JScrollPane scrollPane = new JScrollPane(dialogueTable);
        add(scrollPane, BorderLayout.CENTER);

        // 加载对话记录
        loadDialogueRecords();

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 0));

        addButton = new JButton("添加问答");
        deleteButton = new JButton("删除问答");
        editButton = new JButton("编辑问答");
        saveButton = new JButton("保存");

        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(editButton);
        buttonPanel.add(saveButton);

        // 添加动作监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addDialogue();
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteDialogue();
            }
        });

        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                editDialogue();
            }
        });

        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveChanges();
            }
        });

        add(buttonPanel, BorderLayout.SOUTH);
    }

    // 加载对话记录
//    private void loadDialogueRecords() {
//        tableModel.setRowCount(0); // 清空表格
//        originalDialogues = dialogueManage.loadDialogueLibrary();
//        modifiedDialogues = new ArrayList<>(originalDialogues);
//        for (DialogueDTO dialogue : modifiedDialogues) {
//            tableModel.addRow(new Object[]{dialogue.getId(), dialogue.getQuestion(), dialogue.getAnswer()});
//        }
//        log.info("加载originalDialogues对话记录：{}", originalDialogues);
//        log.info("加载modifiedDialogues对话记录：{}", modifiedDialogues);
//    }
    private synchronized void loadDialogueRecords() {
    tableModel.setRowCount(0); // 清空表格
    originalDialogues = dialogueManage.loadDialogueLibrary();
    modifiedDialogues = new ArrayList<>();
    for (DialogueDTO original : originalDialogues) {
        modifiedDialogues.add(new DialogueDTO(original.getId(), original.getQuestion(), original.getAnswer()));
    }
    for (DialogueDTO dialogue : modifiedDialogues) {
        tableModel.addRow(new Object[]{dialogue.getId(), dialogue.getQuestion(), dialogue.getAnswer()});
    }
    log.info("加载originalDialogues对话记录：{}", originalDialogues);
    log.info("加载modifiedDialogues对话记录：{}", modifiedDialogues);
}


    // 添加问答的方法
    private void addDialogue() {
        String question = JOptionPane.showInputDialog(this, "请输入新的问题:");
        String answer = JOptionPane.showInputDialog(this, "请输入新的答案:");
        if (question != null && !question.trim().isEmpty() && answer != null && !answer.trim().isEmpty()) {
            int newId = modifiedDialogues.isEmpty() ? 1 : modifiedDialogues.get(modifiedDialogues.size() - 1).getId() + 1;
            DialogueDTO newDialogue = new DialogueDTO(newId, question, answer);
            modifiedDialogues.add(newDialogue);
            tableModel.addRow(new Object[]{newDialogue.getId(), newDialogue.getQuestion(), newDialogue.getAnswer()});
            JOptionPane.showMessageDialog(this, "问答已添加");
        }
    }

    // 删除问答的方法
    private void deleteDialogue() {
        int selectedRow = dialogueTable.getSelectedRow();
        if (selectedRow != -1) {
            int id = (int) tableModel.getValueAt(selectedRow, 0);
            int result = JOptionPane.showConfirmDialog(this, "确定要删除选中的问答吗？", "删除问答", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                modifiedDialogues.removeIf(dialogue -> dialogue.getId() == id);
                tableModel.removeRow(selectedRow);
                JOptionPane.showMessageDialog(this, "问答已删除");
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的问答");
        }
    }

    // 编辑问答的方法
//    private void editDialogue() {
//        int selectedRow = dialogueTable.getSelectedRow();
//        if (selectedRow != -1) {
//            int id = (int) tableModel.getValueAt(selectedRow, 0);
//            String currentQuestion = (String) tableModel.getValueAt(selectedRow, 1);
//            String currentAnswer = (String) tableModel.getValueAt(selectedRow, 2);
//
//            String newQuestion = JOptionPane.showInputDialog(this, "编辑问题:", currentQuestion);
//            String newAnswer = JOptionPane.showInputDialog(this, "编辑答案:", currentAnswer);
//
//            if (newQuestion != null && !newQuestion.trim().isEmpty() && newAnswer != null && !newAnswer.trim().isEmpty()) {
//                for (DialogueDTO dialogue : modifiedDialogues) {
//                    if (dialogue.getId() == id) {
//                        dialogue.setQuestion(newQuestion);
//                        dialogue.setAnswer(newAnswer);
//                        break;
//                    }
//                }
//                tableModel.setValueAt(newQuestion, selectedRow, 1);
//                tableModel.setValueAt(newAnswer, selectedRow, 2);
//                JOptionPane.showMessageDialog(this, "问答已更新");
//            }
//        } else {
//            JOptionPane.showMessageDialog(this, "请选择要编辑的问答");
//        }
//    }

    //test
    // 编辑问答的方法
    private synchronized void editDialogue() {
        int selectedRow = dialogueTable.getSelectedRow();
        if (selectedRow != -1) {
            int id = (int) tableModel.getValueAt(selectedRow, 0);
            String currentQuestion = (String) tableModel.getValueAt(selectedRow, 1);
            String currentAnswer = (String) tableModel.getValueAt(selectedRow, 2);

            log.info("Selected Row: {}", selectedRow);
            log.info("Current Question: {}", currentQuestion);
            log.info("Current Answer: {}", currentAnswer);

            String newQuestion = JOptionPane.showInputDialog(this, "编辑问题:", currentQuestion);
            String newAnswer = JOptionPane.showInputDialog(this, "编辑答案:", currentAnswer);

            if (newQuestion != null && !newQuestion.trim().isEmpty() && newAnswer != null && !newAnswer.trim().isEmpty()) {
                log.info("New Question: {}", newQuestion);
                log.info("New Answer: {}", newAnswer);

                for (DialogueDTO dialogue : modifiedDialogues) {
                    if (dialogue.getId() == id) {
                        log.info("Updating dialogue with ID: {}", id);
                        dialogue.setId(id);
                        dialogue.setQuestion(newQuestion);
                        dialogue.setAnswer(newAnswer);

                        //modifiedDialogues.set(originalDialogues.indexOf(dialogue), dialogue);
                        break;
                    }
                }

                // 更新tableModel以保持界面同步
                tableModel.setValueAt(newQuestion, selectedRow, 1);
                tableModel.setValueAt(newAnswer, selectedRow, 2);
                log.info("Table model updated: Question: {}, Answer: {}", newQuestion, newAnswer);
                log.info("modifiedDialogues after update: {}", modifiedDialogues);
                JOptionPane.showMessageDialog(this, "问答已更新");
            } else {
                log.info("New Question or New Answer is empty or null");
            }
        } else {
            log.info("No row selected");
            JOptionPane.showMessageDialog(this, "请选择要编辑的问答");
        }
    }


private void saveChanges() {
    log.info("Starting saveChanges method");

    // 删除已删除的问答
    for (DialogueDTO original : originalDialogues) {
        if (modifiedDialogues.stream().noneMatch(modified -> modified.getId() == original.getId())) {
            log.info("Deleting dialogue with ID: {}", original.getId());
            dialogueManage.deleteDialogue(original.getId());
        }
    }

    // 更新已修改的问答
    log.info("加载originalDialogues对话记录...：{}", originalDialogues);
    log.info("加载modifiedDialogues对话记录...：{}", modifiedDialogues);

    for (DialogueDTO modified : modifiedDialogues) {
        DialogueDTO original = originalDialogues.stream()
                .filter(o -> o.getId() == modified.getId())
                .findFirst()
                .orElse(null);
        if (original != null) {
            if (!original.getQuestion().equals(modified.getQuestion()) ||
                !original.getAnswer().equals(modified.getAnswer())) {
                log.info("Updating dialogue with ID: {}, Question: {}, Answer: {}", modified.getId(), modified.getQuestion(), modified.getAnswer());
                dialogueManage.updateDialogue(modified.getId(), modified.getQuestion(), modified.getAnswer());
            } else {
                log.info("未更新问答: {}, {}, {}", original.getId(), original.getQuestion(), original.getAnswer());
            }
        } else {
            // 添加新的问答
            log.info("Adding new dialogue: {} - {}", modified.getQuestion(), modified.getAnswer());
            dialogueManage.addDialogue(modified.getQuestion(), modified.getAnswer());
        }
    }

    // 重新加载问题模板
    log.info("Reloading question templates");
    questionMatcher.loadQuestionTemplates();

    JOptionPane.showMessageDialog(this, "所有更改已保存");
    dispose();
}



    // 保存更改的方法
//    private void saveChanges() {
//        log.info("开始保存更改");
//        // 删除已删除的问答
//        for (DialogueDTO original : originalDialogues) {
//            if (modifiedDialogues.stream().noneMatch(modified -> modified.getId() == original.getId())) {
//                log.info("删除问答: " + original.getId() + ", " + original.getQuestion() + ", " + original.getAnswer());
//                dialogueManage.deleteDialogue(original.getId());
//            }
//        }
//
//        // 更新已修改的问答
//        for (DialogueDTO modified : modifiedDialogues) {
//            boolean isOriginal = originalDialogues.stream().anyMatch(original -> original.getId() == modified.getId());
//            if (isOriginal) {
//                for (DialogueDTO original : originalDialogues) {
//                    if (original.getId() == modified.getId() &&
//                        (!original.getQuestion().equals(modified.getQuestion()) ||
//                         !original.getAnswer().equals(modified.getAnswer()))) {
//                        log.info("更新问答: " + modified.getId() + ", " + modified.getQuestion() + ", " + modified.getAnswer());
//                        dialogueManage.updateDialogue(modified.getId(), modified.getQuestion(), modified.getAnswer());
//                    }
//                    else {
//                        log.info("未更新问答: " + modified.getId() + ", " + modified.getQuestion() + ", " + modified.getAnswer());
//                    }
//                }
//            } else {
//                // 添加新的问答
//                log.info("添加问答: " + modified.getId() + ", " + modified.getQuestion() + ", " + modified.getAnswer());
//                dialogueManage.addDialogue(modified.getQuestion(), modified.getAnswer());
//            }
//        }
//
//        //重新加载问题模版
//        log.info("reload");//test
//        questionMatcher.loadQuestionTemplates();
//
//        JOptionPane.showMessageDialog(this, "所有更改已保存");
//        dispose();
//    }
}
